#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <iostream>
#include <cmath>
#include <cstdlib>

#include <QDebug>
#include <QVBoxLayout>

namespace {
// 定义一些音频参数
const int SAMPLE_RATE = 44100;  // 采样率
const int CHANNELS = 2;        // 声道数（双声道）
const int BITS_PER_SAMPLE = 16;  // 16位量化
const int DURATION_SECONDS = 10;  // 音频时长（秒）

// 根据量化位数获取数据类型
typedef short SampleType;

void generateSineWaveAudio(SampleType *buffer, int bufferSize) {
    const double PI = 3.14159265358979323846;
    const double amplitude = 32767;  // 对于16位音频，最大幅度
    const double frequency = 440;  // 440Hz频率，可调整为其他频率

    int sampleIndex = 0;
    for (int i = 0; i < bufferSize / (CHANNELS * sizeof(SampleType)); ++i) {
        double time = static_cast<double>(i) / static_cast<double>(SAMPLE_RATE);
        double sineValue = sin(2 * PI * frequency * time);
        for (int channel = 0; channel < CHANNELS; ++channel) {
            buffer[sampleIndex++] = static_cast<SampleType>(sineValue * amplitude);
        }
    }
}

}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_Button = new QPushButton("Play", this);
    connect(m_Button, &QPushButton::clicked, this, &MainWindow::onButtonClicked);

    QVBoxLayout *layout = new QVBoxLayout();
    QWidget* centerWidget = new QWidget();
    centerWidget->setLayout(layout);

    layout->addWidget(m_Button);

    setCentralWidget(centerWidget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

#include "aaudiotester.h"

void MainWindow::onButtonClicked() {
    qDebug() << "Play button clicked.";
    // int bufferSize = SAMPLE_RATE * CHANNELS * BITS_PER_SAMPLE / 8 * DURATION_SECONDS;
    // SampleType *audioBuffer = static_cast<SampleType *>(malloc(bufferSize));
    // if (audioBuffer == nullptr) {
    //     std::cerr << "内存分配失败！" << std::endl;
    //     return;
    // }

    // generateSineWaveAudio(audioBuffer, bufferSize);
    // m_Player.play(audioBuffer, bufferSize, CHANNELS, SAMPLE_RATE);
#if __ANDROID_API__ >=26
    qDebug() << "aaudio avaliable";
    runTest();
#else
    qDebug() << "aaudio unavaliable";
#endif
}
